// events
//  - connected

var xmpp = (function($) {
	var c, state = {index: Strophe.Status.DISCONNECTED }, transitions = [];

	function updateState(index) {
		for (var st in Strophe.Status) {
			if (index === Strophe.Status[st]) {
				state = { index: index, name: st};
			}
		}
	}
	function connectionCallback(s) {
		updateState(s);
		c.trigger(state.name);
		c.trigger('transition', [state]);
	}
	function logStateChange() {
		say(state.name, state.index);
		transitions.push({date: new Date(), msg: state.name });
	}
	function onRequestSubscription(s) {
		say('onRequestSubscription: ' + $(s).attr('type'));
		if ($(s).attr('type') === 'subscribe') {
			c.send($pres({type: 'subscribed', to: $(s).attr('from')}));
		} 

		if ($(s).attr('type') === 'subscribed') {
			cookie.set('confirmed', true); 
			setTimeout(sendPresence, 1000);
			setTimeout(addHandlers, 2000);
		}
	}
	function onMessage(s) {
		var from = $(s).attr('from'), msg = $(s).find('body').text();
		say(from + " says: " + msg);
		epic.flash('info', from + ": " + msg);
		// abuse transitions
		transitions.push({date: new Date(), msg:  from + " " + msg  });
//		var appCtr = Mojo.Controller.getAppController();
//		var stageCtr = appCtr.getStageController(appCtr.assistant.stages.dashboard.name);
//		var sceneCtr = stageCtr.topScene();
//		sceneCtr.serviceRequest('palm://com.palm.applicationManager', {
//			 method:      'open',
//			 parameters:  {
//					 target: msg
//			 }
//		});
		return true;
	}
	function sendPresence() {
		say('sending presence');
		c.send($pres());
	}

	function sendSubscription() {
		if(!cookie.get().confirmed) {
			say('adding subscription request to: ' + cookie.get().admin);
			var s = $pres({type: 'subscribe', to: cookie.get().admin});
			c.addHandler(onRequestSubscription, null, 'presence', 'subscribe');
			c.addHandler(onRequestSubscription, null, 'presence', 'subscribed');
			c.send(s);
		}
	}

	function sendMessage(to, body) {
		var msg = $msg({to: to, type: 'chat'}).c('body').t(body);
		c.send(msg);
		// abuse transitions
		transitions.push({date: new Date(), msg:  to + " " + body  });
	}

	function addHandlers() {
		say('adding msg handlers');
		c.addHandler(onMessage, null, 'message', 'chat');
		sendMessage('epic@' + Strophe.getDomainFromJid(c.jid), 'started .. ');
		setTimeout(function() {
			sendMessage('epic@' + Strophe.getDomainFromJid(c.jid), 'running .. ');
		}, 60 * 1000);
	}


	return {
		connect: function(host, jid, pw) {
			c = jQuery.extend(true, {}, new Strophe.Connection(host), jQuery('<p/>'));
			say(host, jid, pw);
			c.bind('transition', logStateChange);
			c.bind('CONNECTED', sendPresence);
			c.bind('CONNECTED', addHandlers);
			c.bind('CONNECTED', sendSubscription);
			c.connect(jid,pw, connectionCallback);
		}, 
		disconnect: function() {
			if (xmpp.isConnected()) {
				c.send($pres({type: 'unavailable'}));
				c.disconnect();
			}
		},
		bind: function(ev,fn) {
			c.bind(ev,fn);
		},
		trigger: function(ev) {
			c.trigger(ev);
		},
		unbind: function(ev,fn) {
			c.unbind(ev,fn);
		}, 
		isConnected: function() { return state.index === Strophe.Status.CONNECTED ? true : false; },
		isDisconnected: function() { return state.index === Strophe.Status.DISCONNECTED ? true : false; },
		getState: function() { return state; },
		getTransitions: function() { return transitions; }
	};
	
})(jQuery);
